package com.example.hotel_lxy.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hotel_lxy.R;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.DialogHIstoryBean;
import com.example.hotel_lxy.bean.DialogReserveBean;
import com.example.hotel_lxy.bean.EventBusBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.ui.activity.LoginActivity;
import com.example.hotel_lxy.ui.activity.MainActivity;
import com.example.hotel_lxy.ui.activity.ReserveInformationActivity;
import com.example.hotel_lxy.ui.activity.SetUpReserveActivity;
import com.example.hotel_lxy.ui.activity.SetUpZeroPointReserveActivity;
import com.example.hotel_lxy.ui.activity.ZeroPointActivity;
import com.example.hotel_lxy.utils.DatePhotoUtils;
import com.example.hotel_lxy.utils.JurisdictionUtils;
import com.example.hotel_lxy.utils.SPUtils;
import com.example.hotel_lxy.wxapi.WXShare;
import com.ysxsoft.common_base.base.RBaseAdapter;
import com.ysxsoft.common_base.base.RViewHolder;
import com.ysxsoft.common_base.utils.DisplayUtils;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;


/**
 * 预定后
 * create by Sincerly on 9999/9/9 0009
 **/
public class ReserveDialog extends Dialog {
    private Context mContext;
    private TextView text_rz;
    private  static String id;
    RecyclerView rv_reserve;
    private ImageView back;
    private Bitmap bitmap;
    private String director_id;
    private LinearLayout line1;
    private static String data;
    private WXShare wxShare;
    TextView text_set;
    TextView text_td;
    private static int type ;//1 今天  3 未来
    private static int timenoon ;//4 午  5 晚

    boolean modifyall;
    boolean modifypersonal ;

    boolean retreatall ;
    boolean retreatpersonal;

    boolean seatall ;
    boolean seatpersonal ;
    private List<DialogReserveBean.DataBean.ListBean> listBeans=new ArrayList<>();
    public ReserveDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        this.mContext = context;

    }

    private View init() {
        View view = View.inflate(mContext, R.layout.dialog_reserve, null);

        String string6 = SPUtils.get(getContext(), "hotel_mobile", "").toString();
        String string7 = SPUtils.get(getContext(), "hotel_addr", "").toString();

        wxShare = new WXShare(mContext);
        line1=view.findViewById(R.id.line1);
        rv_reserve=view.findViewById(R.id.rv_reserve);
        text_rz=view.findViewById(R.id.text_rz);
         text_set=view.findViewById(R.id.text_set);
         text_td=view.findViewById(R.id.text_td);
        back=view.findViewById(R.id.back);
        String string = SPUtils.get(getContext(), "hotel", "").toString();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wxShare.shareText("客户，您好！"+string+"已为您预订"+data+"\n" +
                        "电话："+string6+"\n" +
                        "地址："+string7+"。");
            }
        });
        //修改
         modifyall = JurisdictionUtils.getModifyall(mContext);
         modifypersonal = JurisdictionUtils.getModifypersonal(mContext);
        //退订
         retreatall = JurisdictionUtils.getRetreatall(mContext);
         retreatpersonal = JurisdictionUtils.getRetreatpersonal(mContext);
         //入座
         seatall = JurisdictionUtils.getSeatall(mContext);
         seatpersonal = JurisdictionUtils.getSeatpersonal(mContext);

        showDataRv();

        //入座
        text_rz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(seatall){
                    initRz();
                }else{
                    if(seatpersonal){
                        boolean getuserid = JurisdictionUtils.getuserid(mContext, director_id);
                        if(getuserid){
                            initRz();
                        }else{
                            ToastUtils.longToast(mContext,"当前账号没有操作权限哦");
                            return;
                        }
                    }else{
                        ToastUtils.longToast(mContext,"当前账号没有操作权限哦");
                        return;
                    }
                }

            }
        });
        //退订
        text_td.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    if(retreatall){
                        UnsubscribeDialog.show(mContext,null).setListener(new UnsubscribeDialog.OnDialogClickListener() {
                            @Override
                            public void onPositiveClick(String s) {
                                if(!s.equals("")){
                                    showDataSeat(2);
                                }

                            }
                        });
                    }else{
                        if(retreatpersonal){
                            boolean getuserid = JurisdictionUtils.getuserid(mContext, director_id);
                            if(getuserid){
                                UnsubscribeDialog.show(mContext,null).setListener(new UnsubscribeDialog.OnDialogClickListener() {
                                    @Override
                                    public void onPositiveClick(String s) {
                                        if(!s.equals("")){
                                            showDataSeat(2);
                                        }

                                    }
                                });
                            }else{
                                ToastUtils.longToast(mContext,"当前账号没有操作权限哦");
                                return;
                            }
                        }else{
                            ToastUtils.longToast(mContext,"当前账号没有操作权限哦");
                            return;
                        }
                    }
            }
        });
        //修改
        text_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(modifyall){
                    SetUpZeroPointReserveActivity.start(id);
                    dismiss();
                }else{
                    if(modifypersonal){
                        boolean getuserid = JurisdictionUtils.getuserid(mContext, director_id);
                        if(getuserid){
                            SetUpZeroPointReserveActivity.start(id);
                            dismiss();
                        }else{
                            ToastUtils.longToast(mContext,"当前账号没有操作权限哦");
                            return;
                        }
                    }else{
                        ToastUtils.longToast(mContext,"当前账号没有操作权限哦");
                        return;
                    }
                }
            }
        });

        return view;
    }

    private void initRz() {
        if(type==3){//未来
            ToastUtils.shortToast(mContext,"不是今天的订单");
            return;
        }else{
            if(timenoon==4){//午
                SimpleDateFormat formatter  =  new  SimpleDateFormat   ("HH:mm");
                Date curDate =  new Date(System.currentTimeMillis());
                String time = "00:00-" + formatter.format(curDate);
                String[] two = time.split("-");
                String[] second = two[1].split(":");
                int secondTotalMinute = Integer.valueOf(second[0]) * 60 + Integer.valueOf(second[1]);
                if (secondTotalMinute<960) {
                    text_rz.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_rz_yes));
                }else{
                    text_rz.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_rz_yes));
                    ToastUtils.shortToast(mContext,"00:00后才可以入座");
                    return;
                }
            }else{//晚
                SimpleDateFormat formatter  =  new  SimpleDateFormat   ("HH:mm");
                Date curDate =  new Date(System.currentTimeMillis());
                String time = "00:00-" + formatter.format(curDate);
                String[] two = time.split("-");
                String[] second = two[1].split(":");
                int secondTotalMinute = Integer.valueOf(second[0]) * 60 + Integer.valueOf(second[1]);
                if (secondTotalMinute>=960&&secondTotalMinute < 1439) {
                    text_rz.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_rz_yes));
                }else{
                    ToastUtils.shortToast(mContext,"16:00后才可以入座");
                    text_rz.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_rz_yes));
                    return;
                }
            }

        }


        TakeYourSeatDialog.show(mContext,null).setListener(new TakeYourSeatDialog.OnDialogClickListener() {
            @Override
            public void onPositiveClick(String s) {
                if(!s.equals("")){
                    showDataSeat(1);
                }
            }
        });

    }

    private void showDataSeat(int type) {
        OkHttpUtils.post()
                .url(Api.POST_ZERO_SEAT)
                .addHeader("flag", SPUtils.get(mContext, "token", "").toString())
                .addParams("id", id+"")
                .addParams("type", type+"")
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "入座预定信息onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "入座预定信息onResponse   " + response);
                        BeanBean beanBean=JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("0")){
                            EventBusBean eventBusBean=new EventBusBean();
                            eventBusBean.setStarttime("");
                            eventBusBean.setType(9);
                            EventBus.getDefault().post(eventBusBean); //普通事件发布
                            ToastUtils.show(mContext,beanBean.getMsg());
                            dismiss();
                        } else if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext. startActivity(intent);
                            return;
                        }
                        else{
                            EventBusBean eventBusBean=new EventBusBean();
                            eventBusBean.setStarttime("");
                            eventBusBean.setType(9);
                            EventBus.getDefault().post(eventBusBean); //普通事件发布
                            ToastUtils.show(mContext,beanBean.getMsg());
                            dismiss();
                        }


                    }
                });
    }

    private void showDataRv() {
        OkHttpUtils.post()
                .url(Api.POST_ORDER_MSG)
                .addHeader("flag", SPUtils.get(mContext, "token", "").toString())
                .addParams("id", id+"")
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "入座预定信息onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "入座预定信息onResponse   " + response);
                        DialogReserveBean dialogReserveBean = JsonUtils.parseByGson(response, DialogReserveBean.class);
                        BeanBean beanBean=JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("0")){
                            director_id=dialogReserveBean.getData().getList().getDirector_id()+"";
                            if(modifyall){
                                text_set.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_xg_yes));
                            }else{
                                if(modifypersonal){
                                    boolean getuserid = JurisdictionUtils.getuserid(mContext, director_id);
                                    if(getuserid){
                                        text_set.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_xg_yes));
                                    }else{
                                        text_set.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_xg_no));
                                    }
                                }else{
                                    text_set.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_xg_no));
                                }
                            }


                            if(retreatall){
                                text_td.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_td_yes));
                            }else{
                                if(retreatpersonal){
                                    boolean getuserid = JurisdictionUtils.getuserid(mContext, director_id);
                                    if(getuserid){
                                        text_td.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_td_yes));
                                    }else{
                                        text_td.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_td_no));
                                    }
                                }else{
                                    text_td.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_td_no));
                                }
                            }

                            if(seatall){
                                text_rz.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_rz_yes));
                            }else{
                                if(seatpersonal){
                                    boolean getuserid = JurisdictionUtils.getuserid(mContext, director_id);
                                    if(getuserid){
                                        if(timenoon==4){//午
                                            SimpleDateFormat formatter  =  new  SimpleDateFormat   ("HH:mm");
                                            Date curDate =  new Date(System.currentTimeMillis());
                                            String time = "00:00-" + formatter.format(curDate);
                                            String[] two = time.split("-");
                                            String[] second = two[1].split(":");
                                            int secondTotalMinute = Integer.valueOf(second[0]) * 60 + Integer.valueOf(second[1]);
                                            if (secondTotalMinute<960) {
                                                text_rz.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_rz_yes));
                                            }else{
                                                text_rz.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_rz_no));
                                            }
                                        }else{//晚
                                            SimpleDateFormat formatter  =  new  SimpleDateFormat   ("HH:mm");
                                            Date curDate =  new Date(System.currentTimeMillis());
                                            String time = "00:00-" + formatter.format(curDate);
                                            String[] two = time.split("-");
                                            String[] second = two[1].split(":");
                                            int secondTotalMinute = Integer.valueOf(second[0]) * 60 + Integer.valueOf(second[1]);
                                            if (secondTotalMinute>=960&&secondTotalMinute < 1439) {
                                                text_rz.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_rz_yes));
                                            }else{
                                                text_rz.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_rz_no));
                                            }
                                        }
                                    }else{
                                        text_rz.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_rz_no));
                                    }
                                }else{
                                    text_rz.setBackgroundDrawable(mContext.getResources().getDrawable(R.mipmap.img_rz_no));
                                }
                            }
                            rv_reserve.setLayoutManager(new LinearLayoutManager(mContext));
                            DialogReserveBean.DataBean.ListBean list = dialogReserveBean.getData().getList();
                            listBeans.add(list);
                            RBaseAdapter<DialogReserveBean.DataBean.ListBean> storeDateDialogBeanRBaseAdapter=new RBaseAdapter<DialogReserveBean.DataBean.ListBean>(mContext,
                                    R.layout.dialog_item_history_order,listBeans) {
                                @Override
                                protected void fillItem(RViewHolder holder,DialogReserveBean.DataBean.ListBean item, int position) {
                                    TextView text_elegant=holder.itemView.findViewById(R.id.text_elegant);
                                    TextView text_name=holder.itemView.findViewById(R.id.text_name);
                                    TextView text_mobile=holder.itemView.findViewById(R.id.text_mobile);
                                    TextView text_people=holder.itemView.findViewById(R.id.text_people);
                                    TextView text_end_time=holder.itemView.findViewById(R.id.text_end_time);
                                    TextView text_content=holder.itemView.findViewById(R.id.text_content);
                                    TextView text_yu_name=holder.itemView.findViewById(R.id.text_yu_name);
                                    TextView text_addtime=holder.itemView.findViewById(R.id.text_addtime);
                                    text_elegant.setText(""+item.getElegant());
                                    if(item.getSex()==1){
                                        text_name.setText(""+item.getName()+"先生");
                                    }else{
                                        text_name.setText(""+item.getName()+"女士");
                                    }
                                    text_mobile.setText(""+item.getMobile());
                                    text_people.setText(""+item.getPeople());
                                    text_end_time.setText(""+item.getEnd_time()+item.getTime());
                                    text_content.setText(""+item.getContent());
                                    text_yu_name.setText(""+item.getDirector());
                                    text_addtime.setText(""+item.getAddtime());
                                    text_mobile.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (DatePhotoUtils.isPhone(item.getMobile() + "")) {
                                                DialPhoneDialog.show(mContext,null,item.getMobile()+"");
                                            } else {
                                                com.luck.picture.lib.tools.ToastUtils.s(mContext, "手机号有误");
                                            }

//                                            Intent intent = new Intent();
//                                            intent.setAction(Intent.ACTION_DIAL);
//                                            intent.setData(Uri.parse("tel:"+item.getMobile()));
//                                            mContext.startActivity(intent);
                                        }
                                    });


                                }

                                @Override
                                protected int getViewType(DialogReserveBean.DataBean.ListBean item, int position) {
                                    return 0;
                                }
                            };
                            rv_reserve.setAdapter(storeDateDialogBeanRBaseAdapter);
                        }
                        else if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                           mContext. startActivity(intent);
                        }
                        else{
                            ToastUtils.show(mContext,beanBean.getMsg());
                            dismiss();
                        }


                    }
                });

    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCanceledOnTouchOutside(true);
//        setCancelable(false);
        setContentView(init());
    }
    public void showDialog() {
        if (!isShowing()) {
            show();
            WindowManager.LayoutParams lp = getWindow().getAttributes();
//            lp.height = DisplayUtils.getDisplayWidth(mContext) * 5 / 5;
            lp.width = DisplayUtils.getDisplayWidth(mContext) * 9 / 10;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            getWindow().setAttributes(lp);
            getWindow().setGravity(Gravity.CENTER);
        }
    }

    public static ReserveDialog show(Context context, OnDialogClickListener listener,String ids,String datas,int types,int timenoons) {
        ReserveDialog dialog = new ReserveDialog(context, R.style.BottomDialogStyle);
        dialog.setListener(listener);
        id=ids;
        data=datas;
        type=types;
        timenoon=timenoons;
        dialog.showDialog();
        return dialog;
    }

    public OnDialogClickListener listener;

    public ReserveDialog setListener(OnDialogClickListener listener) {
        this.listener = listener;
        return this;
    }

    public interface OnDialogClickListener {
        /**
         * 点击确定按钮事件
         */
        public void onPositiveClick(String s);
    }
}